import { Injectable } from '@nestjs/common';
import { InjectDataSource, InjectRepository } from '@nestjs/typeorm';
import { Repository, DataSource } from 'typeorm';
import { FeedbackEntity, FeedbackStatus } from './feedback.entity';
import { CreateFeedbackDto } from './dto/create-feedback.dto';
import { CommonStatus } from '~/common/entity/common.entity';
import { FeedbackPageDto } from './dto/feedback-page.dto';
import { UpdateFeedbackStatusDto } from './dto/update-feedback-status.dto';
import { standardPaginate, StandardPagination } from '~/helper/paginate';
import { BadRequestException } from '@nestjs/common';
import { ErrorEnum } from '~/constants/error-code.constant';
import { isNil } from 'lodash';
import { UserEntity } from '../user/user.entity';
import { UserWechatEntity } from '../user/user-wechat/user-wechat.entity';

@Injectable()
export class FeedbackService {
  constructor(
    @InjectRepository(FeedbackEntity)
    private readonly feedbackRepository: Repository<FeedbackEntity>,
    @InjectDataSource()
    private readonly dataSource: DataSource
  ) {}

  /**
   * 保存反馈
   * @param createFeedbackDto 创建反馈DTO
   * @param userId 用户ID
   * @returns 保存的反馈实体
   */
  async saveFeedback(
    createFeedbackDto: CreateFeedbackDto,
    userId: number
  ): Promise<FeedbackEntity> {
    const feedback = this.feedbackRepository.create({
      content: createFeedbackDto.content,
      status: FeedbackStatus.NEW,
      userId,
      isDeleted: CommonStatus.NO,
    });

    return await this.feedbackRepository.save(feedback);
  }

  /**
   * 分页查询反馈列表
   * @param dto 分页查询参数
   * @returns 分页结果
   */
  async findPage(dto: FeedbackPageDto): Promise<StandardPagination<FeedbackEntity>> {
    const queryBuilder = this.feedbackRepository
      .createQueryBuilder('feedback')
      .select([
        'feedback.id',
        'feedback.content',
        'feedback.type',
        'feedback.status',
        'feedback.replyContent',
        'feedback.handlerId',
        'feedback.handleTime',
        'feedback.userId',
        'feedback.createdAt',
        'feedback.updatedAt',
      ])
      .where('feedback.isDeleted = :isDeleted', { isDeleted: CommonStatus.NO })
      .orderBy('feedback.createdAt', 'DESC');

    // 根据反馈类型筛选
    if (dto.type) {
      queryBuilder.andWhere('feedback.type = :type', { type: dto.type });
    }

    // 根据反馈状态筛选
    if (dto.status) {
      queryBuilder.andWhere('feedback.status = :status', { status: dto.status });
    }

    // 根据反馈内容模糊查询
    if (dto.content) {
      queryBuilder.andWhere('feedback.content LIKE :content', { content: `%${dto.content}%` });
    }

    // 根据用户ID筛选
    if (dto.userId) {
      queryBuilder.andWhere('feedback.userId = :userId', { userId: dto.userId });
    }

    return standardPaginate(queryBuilder, { page: dto.page, pageSize: dto.pageSize });
  }

  /**
   * 更新反馈状态
   * @param id 反馈ID
   * @param dto 更新状态DTO
   * @returns 更新后的反馈实体
   */
  async updateStatus(id: number, dto: UpdateFeedbackStatusDto): Promise<FeedbackEntity> {
    // 检查反馈是否存在
    const existingFeedback = await this.feedbackRepository.findOne({
      where: { id, isDeleted: CommonStatus.NO },
    });

    if (isNil(existingFeedback)) {
      throw new BadRequestException(ErrorEnum.NOT_FOUND);
    }

    // 构建更新数据对象
    const updateData: Partial<FeedbackEntity> = {
      status: dto.status,
      handleTime: new Date(),
    };

    if (dto.replyContent !== undefined) {
      updateData.replyContent = dto.replyContent;
    }

    if (dto.handlerId !== undefined) {
      updateData.handlerId = dto.handlerId;
    }

    // 执行更新
    await this.feedbackRepository.update(id, updateData);

    // 返回更新后的实体
    return await this.feedbackRepository.findOne({
      where: { id },
    });
  }

  /**
   * 软删除反馈
   * @param id 反馈ID
   * @returns void
   */
  async remove(id: number): Promise<void> {
    // 检查反馈是否存在
    const existingFeedback = await this.feedbackRepository.findOne({
      where: { id, isDeleted: CommonStatus.NO },
    });

    if (isNil(existingFeedback)) {
      throw new BadRequestException(ErrorEnum.NOT_FOUND);
    }

    // 软删除：将 isDeleted 设置为 YES
    await this.feedbackRepository.update(id, { isDeleted: CommonStatus.YES });
  }

  /**
   * 获取所有反馈
   * @returns 反馈列表
   */
  async getAllFeedbacks(): Promise<Partial<FeedbackEntity>[]> {
    return await this.dataSource
      .createQueryBuilder()
      .select('feedback.id', 'feedbackId')
      .addSelect('feedback.content', 'feedbackContent')
      .addSelect('feedback.status', 'feedbackStatus')
      .addSelect('feedback.user_id', 'userId')
      .addSelect('feedback.createdAt', 'createdAt')
      .addSelect('userWechat.nickname', 'nickname')
      .addSelect('userWechat.phone', 'phone')
      .from(FeedbackEntity, 'feedback')
      .leftJoin(UserEntity, 'user', 'user.id = feedback.user_id')
      .leftJoin(UserWechatEntity, 'userWechat', 'userWechat.id = user.wechat_id')
      .orderBy('feedback.id', 'DESC')
      .getRawMany();
  }
}
